<?php

namespace services\common;

use common\components\Service;
use common\factory\EasyWeChat;
use common\helpers\CommonHelper;
use common\models\log\LogMessage;
use services\log\LogMessageService;
use Yii;


class MessageService extends Service
{
    /**
     * 发送钉钉消息
     * @param string $code
     * @param array $messageData
     * @return void
     * @throws \Exception
     */
    public static function sendDingtalk(string $code, array $messageData): void
    {
        // 1.钉钉通知
        $url = Yii::$app->params['dingtalk_url']."?t_code={$code}";
        $queryStr = http_build_query($messageData);
        $data = [
            'params' => CommonHelper::encrtyp(urlencode($queryStr)),
        ];
        $res = CommonHelper::https_request($url, $data);
        $sendResult = json_decode($res, true);
        $sendResult = is_array($sendResult) ? $sendResult : [$sendResult];
        LogMessageService::create(LogMessage::TYPE_DINGTALK, $data, $sendResult);
    }

    /**
     * 发送微信消息
     * @param string $templateId
     * @param string $openid
     * @param array $data
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function sendWechat(string $templateId, string $openid, array $data): void
    {
        $sendArray = [
            'template_id' => $templateId, // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的 openid
            'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' =>  $data,   // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        ];
        $app = EasyWeChat::miniProgram();
        $sendResult = $app->subscribe_message->send($sendArray);

        LogMessageService::create(LogMessage::TYPE_WECHAT, $sendArray, $sendResult);
    }
}